package com.san.simulation.listener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.pvm.runtime.ExecutionImpl;
import org.activiti.spring.ProcessEngineFactoryBean;

import com.san.dissertation.bpm.model.Process;
import com.san.dissertation.bpm.model.ProcessInstance;
import com.san.dissertation.bpm.model.Task;
import com.san.dissertation.dao.service.impl.DAOServiceImpl;

public class UserManualEventExecutionListener implements ExecutionListener {

	private DAOServiceImpl daoServiceImpl;
	private RepositoryService repositoryService;

	public void notify(DelegateExecution execution) throws Exception {
		// TODO Auto-generated method stub

		String instanceId = execution.getProcessInstanceId();
		Map<String, Object> varMap = execution.getVariables();

		String processKey = execution.getProcessDefinitionId().substring(0,
				execution.getProcessDefinitionId().indexOf(":"));
		
		Process process = daoServiceImpl.getProcessRepository().findByKey(
				processKey);

		if (execution.getEventName().equals(EVENTNAME_START)) {

System.out.println(instanceId+"iid");
			ProcessInstance instance = daoServiceImpl.getProcessInstanceRepository().getProcessInstanceById(instanceId);
			instance.setVariable(execution.getVariables());
			List<Task> tasks = instance.getTask();
			Task task = new Task();
			task.setId(execution.getCurrentActivityId());
			task.setKey(task.getId());
			task.setName(execution.getCurrentActivityName());
			task.setStartDate(new Date());
			tasks.add(task);
			instance.setTask(tasks);

			daoServiceImpl.getProcessInstanceRepository().save(instance);

		} else if (execution.getEventName().equals(EVENTNAME_END)) {
			System.out.println(EVENTNAME_END + "********************"+execution.getCurrentActivityId());
			// daoServiceImpl.getProcessRepository().updateTaskEndById(instanceId,
			// execution.getCurrentActivityId());
			
			daoServiceImpl.getProcessInstanceRepository().updateStartTaskEnd(process, execution.getCurrentActivityId());
			
		}

		System.out.println("Start event execution listener : " + instanceId);

	}

	public DAOServiceImpl getDaoServiceImpl() {
		return daoServiceImpl;
	}

	public void setDaoServiceImpl(DAOServiceImpl daoServiceImpl) {
		this.daoServiceImpl = daoServiceImpl;
	}

}
